package org.liuyunfeng.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: TanJingyu
 * @create: 2022-03-07 10:26
 **/
@RestController
@RequestMapping("/cookie")
public class CookieController {

    @GetMapping
    public String cookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName());
                System.out.println(cookie.getValue());
                System.out.println(cookie.getDomain());
                System.out.println(cookie.getPath());
            }
        }

//        Cookie cookie = new Cookie("test", "666666");
//        cookie.setPath("/cookie");
//        response.addCookie(cookie);

        return request.getRemoteAddr();
    }

    /**
     * cookie的跨域规则
     * 不同域的cookie，浏览器不会带上
     * 默认不设置domain，那么生成的cookie只能用作请求来的这个域，例如从a.codert.com来的，那么b.codert.com和c.a.codert.com都不能访问
     * 想访问，就设置domain，浏览器会设置上点开头的，子域就会共享了
     */
    @GetMapping("/g")
    public String generate(HttpServletResponse response) {
        Cookie cookie = new Cookie("tanjingyu", "666666");
//        cookie.setDomain("qiye.qianlima.com");
        cookie.setPath("/");

        response.addCookie(cookie);

//        response.setHeader("Set-Cookie", "widget_session=abc123; Domain=codert.com; Path=/; SameSite=None; Secure");

        return "success...";
    }

    @GetMapping("/g2")
    public String generate2(HttpServletResponse response) {
        Cookie cookie = new Cookie("tanjingyu", "666666");
        cookie.setDomain("new.pc.qiye.qianlima.com");
        cookie.setPath("/");

        response.addCookie(cookie);

//        response.setHeader("Set-Cookie", "widget_session=abc123; Domain=codert.com; Path=/; SameSite=None; Secure");

        return "success...";
    }

    @GetMapping("/baidu")
    public String baidu(HttpServletResponse response) {
        Cookie cookie = new Cookie("baidu-test", "666666");
        cookie.setDomain("baidu.com");
        cookie.setPath("/");

        response.addCookie(cookie);

//        response.setHeader("Set-Cookie", "widget_session=abc123; Domain=codert.com; Path=/; SameSite=None; Secure");

        return "success...";
    }
}

    